package provider

import (
	"OJCenter/global"
	"OJCenter/idl"
	"OJCenter/model"
	"encoding/json"
	"github.com/nsqio/go-nsq"
)

var nsqP *nsq.Producer
var nsqC *nsq.Consumer

func NsqInit() {
	C := nsq.NewConfig()
	nsqC, _ = nsq.NewConsumer(global.Conf.NsqProvider.ConTopic, global.Conf.NsqProvider.ConChannel, C)
	nsqP, _ = nsq.NewProducer(global.Conf.NsqProvider.Addr, C)
	err := nsqP.Ping()
	if err != nil {
		// 关闭生产者
		global.Logger.Error(global.Conf.NsqProvider.Addr)
		global.Logger.Errorf("nsq init failed,err:%v", err)
		nsqP.Stop()
		nsqP = nil
		return
	}

}

func SendJMessage(message idl.JMessage) {
	_message, err := json.Marshal(&message)
	if err != nil {
		global.Logger.Errorf("sendJmessage marshal failed,err:%v", err)
		return
	}
	err = nsqP.Publish(global.Conf.NsqProvider.Addr, _message)
	if err != nil {
		global.Logger.Errorf("sendJmessage publish failed,err:%v", err)
		return
	}
}

func DoConsume(m *model.Model) {
	defer func() {
		nsqC.Stop()
	}()
	nsqC.AddHandler(nsq.HandlerFunc(m.ConsumeJMessage))
	err := nsqC.ConnectToNSQLookupds(global.Conf.NsqProvider.NsqLookUpAddr)
	if err != nil {
		global.Logger.Errorf("can not find nsq!,err:%v", err)
		return
	}
	<-nsqC.StopChan
}
